<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');

try {
    // 获取指定日期的团课列表
    $sql = "SELECT 
            c.id,
            c.name,
            c.cover_image,
            c.description,
            c.capacity,
            c.booked_count,
            c.duration,
            c.price,
            c.course_date,
            c.start_time,
            c.end_time,
            cc.name as category_name,
            co.name as coach_name,
            co.avatar as coach_avatar
            FROM courses c
            LEFT JOIN course_categories cc ON c.category_id = cc.id
            LEFT JOIN coaches co ON c.coach_id = co.id
            WHERE c.course_date = ?
            AND c.status = 1
            AND (
                c.course_date > CURDATE()
                OR (c.course_date = CURDATE() AND c.start_time >= TIME(NOW()))
            )
            ORDER BY c.start_time ASC";
            
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    $courses = [];
    while ($row = $result->fetch_assoc()) {
        // 格式化时间
        $row['start_time'] = date('H:i', strtotime($row['start_time']));
        $row['end_time'] = date('H:i', strtotime($row['end_time']));
        
        // 计算课程状态
        $course_datetime = strtotime($row['course_date'] . ' ' . $row['start_time']);
        $now = time();
        
        if ($row['booked_count'] >= $row['capacity']) {
            $row['status'] = [
                'code' => 'full',
                'text' => '已满'
            ];
        } else if ($course_datetime <= $now) {
            $row['status'] = [
                'code' => 'started',
                'text' => '已开始'
            ];
        } else {
            $row['status'] = [
                'code' => 'available',
                'text' => '可预约'
            ];
        }
        
        // 检查用户是否已预约
        if (isset($_GET['user_id'])) {
            $check_sql = "SELECT id FROM bookings 
                         WHERE user_id = ? AND course_id = ? 
                         AND booking_date = ? AND status != 3";
            $check_stmt = $conn->prepare($check_sql);
            $check_stmt->bind_param("iis", $_GET['user_id'], $row['id'], $date);
            $check_stmt->execute();
            $row['is_booked'] = $check_stmt->get_result()->num_rows > 0;
            $check_stmt->close();
        }

        $courses[] = $row;
    }
    
    echo json_encode([
        'status' => 'success',
        'list' => $courses,
        'total' => count($courses)
    ]);

} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    $conn->close();
}
?> 